package cn.flying.cloud.flow.core.listener.event.callback;

import javax.annotation.Resource;

import org.flowable.bpmn.model.UserTask;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.event.impl.FlowableActivityEventImpl;
import org.flowable.engine.impl.bpmn.behavior.ParallelMultiInstanceBehavior;
import org.flowable.engine.impl.bpmn.behavior.SequentialMultiInstanceBehavior;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import cn.flying.cloud.base.common.utils.Ft;
import cn.flying.cloud.flow.bo.FwProcInstBo;
import cn.flying.cloud.flow.core.constants.FlowableConstant;
import cn.flying.cloud.flow.core.listener.handler.UserHandler;
import cn.flying.cloud.flow.service.FwProcInstService;

/**
 * 活动开始监听
 *
 * @author: admin
 * @date: 2023年02月26日 08:21
 * @version: 1.0
 */
@Component
public class ActivityStartedListenerCallback implements EventListenerCallback {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private FwProcInstService procInstService;
    @Resource
    private UserHandler userHandler;

    /**
     * 设置任务的代理人，通过在绘制流程图的时候配置${assignee}变量的在这里设置
     *
     * @param event
     */
    @Override
    public void execute(FlowableEvent event) {
        logger.info("==========活动开始监听器回调处理---start===========");
        // FlowableEngineEventImpl
        logger.info("监听事件类型：【{}】", event.getType().name());
        FlowableActivityEventImpl entityEvent = (FlowableActivityEventImpl) event;

        String behaviorClass = entityEvent.getBehaviorClass();
        if (behaviorClass.equals(ParallelMultiInstanceBehavior.class.getName())) {
            logger.info("并行多实例活动，当前不处理！");
            logger.info("==========活动开始监听器回调处理---end===========");
            return;
        } else if (behaviorClass.equals(SequentialMultiInstanceBehavior.class.getName())) {
            logger.info("并行多实例活动，当前不处理！");
            logger.info("==========活动开始监听器回调处理---end===========");
            return;
        }

        FwProcInstBo inst = new FwProcInstBo();
        inst.setProcInstId(entityEvent.getProcessInstanceId());
        inst = procInstService.getOneObj(inst);
        inst.setNodeId(entityEvent.getActivityId());
        inst.setNodeName(entityEvent.getActivityName());
        procInstService.updateObj(inst);

        if (!"userTask".equals(entityEvent.getActivityType())) {
            logger.info("==========活动开始监听器回调处理---end===========");
            return;
        }
        DelegateExecution execution = entityEvent.getExecution();
        // 检查任务是否有指定的代理人
        String assignee = ((UserTask) (execution.getCurrentFlowElement())).getAssignee();
        // 如果使用了变量表达式，则可以通过表达式来设置
        // 过滤掉不是设置了${assignee}的
        if (assignee == null || !assignee.contains("${assignee}")) {
            logger.info("==========活动开始监听器回调处理---end===========");
            return;
        }

        String userId = userHandler.getAssignee(entityEvent.getProcessDefinitionId(), entityEvent.getActivityId());
        if (Ft.String.isBlank(userId)) {
            logger.info("==========活动开始监听器回调处理---end===========");
            return;
        }

        execution.setVariable(FlowableConstant.ASSIGNEE, assignee);
        logger.info("流程实例：【{}】任务；[{}，{}]分配代理人：【{}】", entityEvent.getProcessInstanceId(), entityEvent.getActivityName(), entityEvent.getActivityId(), assignee);

        logger.info("==========活动开始监听器回调处理---end===========");
    }
}
